// SPDX-License-Identifier: GPL-2.0+
/*
 * Simple xorshift PRNG
 *   see http://www.jstatsoft.org/v08/i14/paper
 *
 * Copyright (c) 2012 Michael Walle
 * Michael Walle <michael@walle.cc>
 */
#include <utils/random.h>

static uint64_t y = 1;

static uint64_t random_r(uint64_t *seedp)
{
    *seedp ^= (*seedp << 13);
    *seedp ^= (*seedp >> 17);
    *seedp ^= (*seedp << 5);

    return *seedp;
}

uint64_t utils_random(void)
{
    return random_r(&y);
}

uint64_t utils_random_range(uint64_t min, uint64_t max)
{
    uint64_t temp;

    if (unlikely(min > max))
        return 0;

    if (unlikely(min == max))
        return min;

    temp = max - min + 1;

    return min + (utils_random() % temp);
}

void utils_srand(uint64_t seed)
{
    y = seed;
}
